package com.example.yaseademo.utils;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClientInputThread extends Thread {
    private Socket socket;
    private String msg;
    private boolean isStart = true;
    private InputStream ois;
    private DataInputStream dis;
    private MessageListener messageListener;// 消息监听接口对象

    public ClientInputThread(Socket socket) {
        this.socket = socket;
        try {
            ois = socket.getInputStream();
            dis = new DataInputStream(new BufferedInputStream(ois));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提供给外部的消息监听方法
     *
     * @param messageListener
     *            消息监听接口对象
     */
    public void setMessageListener(MessageListener messageListener) {
        this.messageListener = messageListener;
    }

    public void setStart(boolean isStart) {
        this.isStart = isStart;
    }

    @Override
    public void run() {
        try {
            while (isStart) {
                //读取信息,如果没信息将会阻塞线程
                msg =  dis.readUTF();
                // 每收到一条消息，就调用接口的方法Message(String msg)
                Log.v("收到消息", msg);
                messageListener.Message(msg);
            }
            ois.close();
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    BufferedReader reader=null;
    public String getInputStreamString() {
        /*
         * To convert the InputStream to String we use the
         * BufferedReader.readLine() method. We iterate until the BufferedReader
         * return null which means there's no more data to read. Each line will
         * appended to a StringBuilder and returned as String.
         */
        if (ois != null) {
            reader = new BufferedReader(new InputStreamReader(ois));
        }
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
}